package com.zt.english.activity

import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.speech.tts.Voice
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.zt.english.R
import java.util.*

/**
 * TTS: 使用Android原生api实现文本转语音
 */
class TtsDemoActivity : AppCompatActivity(),TextToSpeech.OnInitListener{
    lateinit var editText:EditText
    lateinit var tts:TextToSpeech
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_tts)
        editText = findViewById(R.id.edit)
        //创建tts对象
        tts = TextToSpeech(this,this)
    }
    fun readClick(view :View){
        val str: String = editText.getText().toString().trim()
        if (!TextUtils.isEmpty(str)) {
            // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
            tts.setPitch(1.0f)
            // 设置语速
            tts.setSpeechRate(1.0f)
            tts.voice = Voice("",Locale("english"),100,1,true,null)
            //播放语音
            tts.speak(str, TextToSpeech.QUEUE_ADD, null, null)
        }
    }

    override fun onInit(status: Int) {
        //判断tts回调是否成功
        if (status === TextToSpeech.SUCCESS) {
            val result1 = tts.setLanguage(Locale.US)
            val result2 = tts.setLanguage(Locale.CHINESE)
            if (result1 == TextToSpeech.LANG_MISSING_DATA || result1 == TextToSpeech.LANG_NOT_SUPPORTED || result2 == TextToSpeech.LANG_MISSING_DATA || result2 == TextToSpeech.LANG_NOT_SUPPORTED) {
                Toast.makeText(this, "数据丢失或不支持", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //停止，关闭tts
        tts.stop()
        tts.shutdown()
    }
}